<?php
/**
 * 通用函数文件
 */

// session已在config.php中启动

// 过滤输入数据
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// 生成随机字符串
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

// 验证邮箱格式
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

// 验证手机号格式（中国大陆手机号）
function validatePhone($phone) {
    return preg_match('/^1[3-9]\d{9}$/', $phone);
}

// 获取用户信息
function getUserInfo($userId) {
    $db = Database::getInstance();
    $user = $db->fetch("SELECT * FROM users WHERE id = ?", [$userId]);
    return $user;
}

// 获取用户头像URL
function getUserAvatar($avatar) {
    if (empty($avatar) || $avatar == 'default.svg') {
        return SITE_URL . '/uploads/avatars/default.svg';
    }
    
    // 检查头像路径是否已经包含uploads/avatars
    if (strpos($avatar, 'uploads/avatars/') === 0) {
        return SITE_URL . '/' . $avatar;
    } else {
        return SITE_URL . '/uploads/avatars/' . $avatar;
    }
}

// 这些函数已在config.php中定义

// 格式化日期时间
function formatDateTime($datetime, $format = 'Y-m-d H:i') {
    $date = new DateTime($datetime);
    return $date->format($format);
}

// 计算剩余时间
function getRemainingTime($deadline) {
    $now = new DateTime();
    $deadlineDate = new DateTime($deadline);
    $interval = $now->diff($deadlineDate);
    
    if ($interval->invert) {
        return '已过期';
    }
    
    if ($interval->days > 0) {
        return $interval->days . '天后';
    } elseif ($interval->h > 0) {
        return $interval->h . '小时后';
    } else {
        return $interval->i . '分钟后';
    }
}

// 显示提示消息
function showAlert($message, $type = 'info') {
    echo '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">';
    echo $message;
    echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
    echo '</div>';
}
